package com.ticketstore.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.ticketstore.dao.IOrderDao;
import com.ticketstore.domain.Order;

@Repository("orderDao")
public class OrderDao implements IOrderDao{
	private OrderDao orderDao = null;
	@Resource
	private SessionFactory sessionFactory = null;
	private OrderDao(){
		
	}
	
	public OrderDao getInstance(){
		if(orderDao == null){
			orderDao = new OrderDao();
		}
		return orderDao;
	}

	@Override
	public boolean insertOrder(Order order) {
		Session session = null;
		Transaction transaction = null;
		Date orderDate = new Date();
		System.out.println(orderDate);
		order.setOrderDate(orderDate);
		order.setTotalPrice(order.getOrderTicketNum()*order.getBusSchedule().getPriceForASeat());
		try{
			session = sessionFactory.getCurrentSession();
			transaction = session.beginTransaction();
			session.save(order);
			transaction.commit();
			return true;
		}catch(Exception e){
			if(transaction != null){
				transaction.rollback();
				e.printStackTrace();
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> listOrderForUser(Integer userID) {
		List<Order> orderList = new ArrayList<Order>();
		Session session = null;
		Transaction transaction = null;
		try{
			session = sessionFactory.getCurrentSession();
			transaction = session.beginTransaction();
			orderList = (List<Order>) session.createQuery("from Order where userID=:uID").setParameter("uID", userID).list();
			transaction.commit();
			return orderList;
		}catch(Exception e){
			if(transaction != null){
				transaction.rollback();
				e.printStackTrace();
			}
			return null;
		}
	}
	
	
}
